import os,sys
from w1_ui import Ui_MainWindow
from PySide6.QtWidgets import QWidget,QApplication,QMainWindow, QTableWidgetItem, QLabel,QTableWidget
from PySide6.QtCore import Qt,QEvent,QMimeData
from PySide6.QtGui import QColor,QMouseEvent,QDrag
from tableclass import basetable
class mywin(QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        self.table=basetable(cols=5,rows=15)
        self.ui.verticalLayout_3.addWidget(self.table)


        self.table2=TeacherList(cols=5,rows=70)
        self.ui.verticalLayout_2.addWidget(self.table2)
        self.table.setStyleSheet("""
        QTableWidget::item:selected {
            background-color: white;  /* 深蓝色背景 */
            color: black;               /* 白色文字 */
        }

    """)

        self.table.setAcceptDrops(True)

        #填充表格内容
        for i in range(self.table.rowCount()):
            for n in range(self.table.columnCount()):
                    item=QTableWidgetItem(f"{i},{n}")
                    self.table.setItem(i,n,item)
        self.setWindowTitle("监考表")
        self.ui.label.setText("1234")
        self.table.setSpan(0,1,1,2)#合并单元格
        # self.table.viewport().installEventFilter(self)
        # self.ui.tableWidget_2.viewport().installEventFilter(self)
        # self.table.setMouseTracking(True)
        # 记录当前按下的单元格位置
        self.pressed_row = -1
        self.pressed_col = -1
        self.status_label=self.ui.label_2
        self.table.setSelectionMode(QTableWidget.NoSelection)
        # self.ui.tableWidget_2.setSelectionMode(QTableWidget.NoSelection)
        self.num=2
        self.columnColor()
        item=self.table.item(3,3)
        item.setBackground(QColor("#4096ff"))
        self.ui.pushButton_4.clicked.connect(self.columnColor)


    def columnColor(self):
        for i in range(self.table.rowCount()):
            for n in range(1,self.table.columnCount()):
                if((n-1)%(self.num*2) < self.num):
                    bakcolor_=QColor('#f0f0f0')
                else:
                    bakcolor_=QColor('#ffffff')


                item=self.table.item(i,n)
                if item is not None:
                    item.setBackground(bakcolor_)
                else:
                    item=QTableWidgetItem("")
                    item.setBackground(bakcolor_)
                    self.table.setItem(i,n,item)


    # def eventFilter(self, obj, event):
    #     if obj == self.table.viewport() and  event.type() == QEvent.MouseMove:
    #         pos = event.pos()
    #         index  = self.table.indexAt(pos)
    #         # self.columnColor()
    #         if index.isValid():
    #             # 注意：行和列都是从0开始的
    #             row = index.row() + 1  # 转换为1-based索引
    #             col = index.column() + 1
    #             self.ui.label.setText(f"鼠标位置: 行 {row}, 列 {col}")
                
    #         else:
    #             self.ui.label.setText("鼠标位置: 不在单元格上")
        
    #     if obj == self.table.viewport() or obj == self.ui.tableWidget_2.viewport():
    #         # 处理左键按下事件
    #         if event.type() == QEvent.MouseButtonPress and event.button() == Qt.LeftButton:
    #             return self.handle_press_event(event)
            
    #         # 处理左键释放事件
    #         elif event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
    #             return self.handle_release_event(event)
        
    #     # 其他事件正常传播
    #     return super().eventFilter(obj, event)
    
    def handle_press_event(self, event: QMouseEvent):
        """处理左键按下事件"""
        pos = event.pos()
        index = self.table.indexAt(pos)
        
        if index.isValid():
            row, col = index.row(), index.column()
            self.pressed_row, self.pressed_col = row, col  # 记录按下位置
            
            # 更新状态
            item_text = self.table.item(row, col).text()
            self.status_label.setText(f"左键按下: 行 {row+1}, 列 {col+1} | 内容: {item_text}")
            
            # 视觉反馈：临时改变单元格背景
            self.original_bg = self.table.item(row, col).background()
            self.table.item(row, col).setBackground(QColor("#ff851b"))
        
        return False  # 不阻止默认行为
    
    def handle_release_event(self, event: QMouseEvent):
        """处理左键释放事件"""
        # 只有之前有按下记录时才处理
        if self.pressed_row != -1 and self.pressed_col != -1:
            row, col = self.pressed_row, self.pressed_col
            
            # 恢复单元格背景
            if self.table.item(row, col):
                self.table.item(row, col).setBackground(self.original_bg)
            
            # 检查释放位置是否与按下位置相同（判断是否为点击）
            release_index = self.table.indexAt(event.pos())
            is_click = (release_index.isValid() and 
                       release_index.row() == row and 
                       release_index.column() == col)
            
            # 更新状态
            action = "点击" if is_click else "拖拽释放"
            self.status_label.setText(f"左键释放: 行 {release_index.row() +1}, 列 {release_index.column()+1} | 操作: {action}")
            
            # 重置记录
            self.pressed_row, self.pressed_col = -1, -1
        else:
            release_index = self.table.indexAt(event.pos())
            self.status_label.setText(f"左键释放(2): 行 {release_index.row() +1}, 列 {release_index.column()+1} ")
        return False
class TeacherList(QTableWidget):
    def __init__(self, parent=None, rows=5, cols=3):
        super().__init__(rows, cols, parent)
        
        # 基础设置
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(QTableWidget.DragOnly)
        self.setHorizontalHeaderLabels([f"列 {i+1}" for i in range(cols)])
        self.setDefaultDropAction(Qt.CopyAction)
        self.prohibited_cells = {
            (0, 0),  # 行索引从0开始
            (2, 0), (2, 1), (2, 2), (2, 3),  # 第3行（索引2）所有列
            (3, 1)   # 第4行第2列
        }
        # 初始化数据
        self._init_data()
        
    def _init_data(self):
        """初始化表格数据"""
        for row in range(self.rowCount()):
            for col in range(self.columnCount()):
                item = QTableWidgetItem(f"数据 ({row+1},{col+1})")
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(row, col, item)
                # 标记禁止拖入的单元格（黄色背景）
                if (row, col) in self.prohibited_cells:
                    item.setBackground(QColor(255, 255, 204))
                    item.setToolTip("禁止拖入")
                self.setItem(row, col, item)
if __name__ =="__main__":
    app=QApplication()
    mywi=mywin()
    mywi.show()
    sys.exit(app.exec())